package com.gy.assistant.ui.friend;

import static android.widget.LinearLayout.VERTICAL;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import im.zego.zim.ZIM;
import im.zego.zim.callback.ZIMBlacklistUsersAddedCallback;
import im.zego.zim.callback.ZIMFriendAliasUpdatedCallback;
import im.zego.zim.callback.ZIMFriendAttributesUpdatedCallback;
import im.zego.zim.callback.ZIMFriendsDeletedCallback;
import im.zego.zim.callback.ZIMFriendListQueriedCallback;
import im.zego.zim.entity.ZIMError;
import im.zego.zim.entity.ZIMErrorUserInfo;
import im.zego.zim.entity.ZIMFriendDeleteConfig;
import im.zego.zim.entity.ZIMFriendInfo;
import im.zego.zim.entity.ZIMFriendListQueryConfig;
import im.zego.zim.enums.ZIMFriendDeleteType;
import com.gy.assistant.MyApplication;
import com.gy.assistant.R;
import com.gy.assistant.SDKManager;
import com.gy.assistant.ui.chat.peer.ZIMPeerChatActivity;
import com.gy.assistant.ui.friend.adapter.FriendListAdapter;
import com.gy.assistant.util.AppLogger;
import java.util.ArrayList;
import java.util.HashMap;

public class ZIMFriendFragment extends Fragment implements ZIMFriendListQueriedCallback {

    private static final String TAG = "ZIMFriendFragment";

    public FriendListAdapter friendListAdapter;

    @Override
    public void onResume() {
        super.onResume();
        ZIMFriendListQueryConfig config = new ZIMFriendListQueryConfig();
        config.count = 3000;
        ZIM.getInstance().queryFriendList(config, this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_address_book_list, container, false);

        RecyclerView conversationRecyclerView = rootView.findViewById(R.id.address_book_list);

        LinearLayoutManager linearLayoutManager =
            new LinearLayoutManager(this.getContext(), LinearLayoutManager.VERTICAL, false);
        conversationRecyclerView.setLayoutManager(linearLayoutManager);
        friendListAdapter = new FriendListAdapter();
        conversationRecyclerView.setItemAnimator(new DefaultItemAnimator());
        conversationRecyclerView.setAdapter(friendListAdapter);

        setHasOptionsMenu(true);

        ZIMFriendListQueryConfig config = new ZIMFriendListQueryConfig();
        config.count = 3000;

        ZIM.getInstance().queryFriendList(config, this);

        friendListAdapter.setOnItemClickListener(new FriendListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, ZIMFriendInfo zimFriendInfo) {
                // 跳转到单聊界面
                ZIMPeerChatActivity.actionStart(getActivity(), zimFriendInfo.userID,
                                                zimFriendInfo.userName,"");
            }
        });

        friendListAdapter.setHeaderOnClickListener(new FriendListAdapter.HeaderItemClickListener() {
            @Override
            public void onItemFriendRequestList() {
                ZIMFriendRequestListActivity.actionStart(getActivity());
            }

            @Override
            public void onItemBlacklist() {
                ZIMBlacklistActivity.actionStart(getActivity());

            }
        });

        friendListAdapter.setOnItemLongClickListener(
            new FriendListAdapter.OnItemLongClickListener() {
                @Override
                public void onItemRemove(View view, ZIMFriendInfo zimFriendInfo) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    String[] item = new String[] {
                        "BOTH DELETE",
                        "SINGLE DELETE",
                        "UPDATE FRIEND INFO",
                        "ADD TO BLACKLIST",

                    };

                    builder.setSingleChoiceItems(item, 0, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if(which ==3){

                                ArrayList<String> userIDs = new ArrayList<>();
                                userIDs.add(zimFriendInfo.userID);
                                ZIM.getInstance().addUsersToBlacklist(userIDs, new ZIMBlacklistUsersAddedCallback() {
                                    @Override
                                    public void onBlacklistUsersAdded(ArrayList<ZIMErrorUserInfo> userIDs, ZIMError error) {
                                        AppLogger.getInstance().d(
                                                "onBlacklistUsersAdded userIDs: %s error: %s",
                                                new Gson().toJson(userIDs),  new Gson().toJson(error));
                                        Toast.makeText(ZIMFriendFragment.this.getContext(),  error.message, Toast.LENGTH_LONG).show();
                                    }
                                });
                                dialog.dismiss();
                                return;
                            }

                            if (which == 2) {
                                EditText friendAttributeKey = new EditText(MyApplication.getCurrentActivity());
                                EditText friendAttributeValue = new EditText(MyApplication.getCurrentActivity());
                                EditText alias = new EditText(MyApplication.getCurrentActivity());
                                EditText wording = new EditText(MyApplication.getCurrentActivity());
                                friendAttributeKey.setHint("input friend attribute key");
                                friendAttributeValue.setHint("input friend attribute value");
                                alias.setHint("input friend alias");
                                wording.setHint("input friend wording");
                                LinearLayout layout = new LinearLayout(MyApplication.getCurrentActivity());
                                layout.setOrientation( VERTICAL);
                                layout.addView(friendAttributeKey);
                                layout.addView(friendAttributeValue);
                                layout.addView(alias);
                                layout.addView(wording);
                                new AlertDialog.Builder(MyApplication.getCurrentActivity())
                                        .setTitle("Update Friend Info")
                                        .setView(layout)
                                        .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                String key = friendAttributeKey.getText().toString();
                                                String value = friendAttributeValue.getText().toString();
                                                String aliasS = alias.getText().toString();
                                                String wordingS = wording.getText().toString();
                                                if(!key.equals("")) {
                                                    HashMap<String, String> friendAttributeMap = new HashMap<>();
                                                    ZIM.getInstance().updateFriendAttributes(friendAttributeMap, zimFriendInfo.userID, new ZIMFriendAttributesUpdatedCallback() {
                                                        @Override
                                                        public void onFriendAttributesUpdated(ZIMFriendInfo friendInfo, ZIMError zimError) {
                                                            AppLogger.getInstance().d(
                                                                    "onFriendAttributesUpdated friendInfo: %s",
                                                                    new Gson().toJson(friendInfo));
                                                            ZIMFriendListQueryConfig config = new ZIMFriendListQueryConfig();
                                                            config.count = 3000;
                                                            ZIM.getInstance().queryFriendList(config, ZIMFriendFragment.this);
                                                        }
                                                    });
                                                }

                                                ZIM.getInstance().updateFriendAlias(aliasS, zimFriendInfo.userID, new ZIMFriendAliasUpdatedCallback() {
                                                    @Override
                                                    public void onFriendAliasUpdated(ZIMFriendInfo friendInfo, ZIMError zimError) {
                                                        AppLogger.getInstance().d(
                                                                "onFriendAliasUpdated friendInfo: %s",
                                                                new Gson().toJson(friendInfo));
                                                        ZIMFriendListQueryConfig config = new ZIMFriendListQueryConfig();
                                                        config.count = 3000;
                                                        ZIM.getInstance().queryFriendList(config, ZIMFriendFragment.this);
                                                    }
                                                });

                                                dialog.dismiss();
                                            }
                                        })
                                        .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }
                                        })
                                        .show();
                                dialog.dismiss();
                                return;
                            }
                            ZIMFriendDeleteConfig zimFriendDeleteConfig =
                                new ZIMFriendDeleteConfig();
                            if (which == 0) {
                                zimFriendDeleteConfig.type = ZIMFriendDeleteType.BOTH;
                            } else {
                                zimFriendDeleteConfig.type = ZIMFriendDeleteType.SINGLE;
                            }
                            ArrayList<String> arrayList = new ArrayList<>();
                            arrayList.add(zimFriendInfo.userID);

                            ZIM.getInstance().deleteFriends(
                                arrayList, zimFriendDeleteConfig, new ZIMFriendsDeletedCallback() {
                                    @Override
                                    public void onFriendsDeletedCallback(
                                        ArrayList<ZIMErrorUserInfo> errorUserList,
                                        ZIMError zimError) {
                                        Toast
                                            .makeText(ZIMFriendFragment.this.getContext(),
                                                      zimError.message, Toast.LENGTH_LONG)
                                            .show();
                                        AppLogger.getInstance().d(
                                                "onFriendDeletedCallback errorUserList: %s, zimError: %s",
                                                new Gson().toJson(errorUserList), new Gson().toJson(zimError));
                                        ZIMFriendListQueryConfig config = new ZIMFriendListQueryConfig();
                                        config.count = 3000;
                                        ZIM.getInstance().queryFriendList(config, ZIMFriendFragment.this);
                                    }
                                });
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                }
            });

        SDKManager.sharedInstance().setFriendEventCallBackCallBack(
            new SDKManager.OnFriendEventCallBack() {
                @Override
                public void onFriendInfoUpdated(ZIM zim, ArrayList<ZIMFriendInfo> friendInfoList) {
                    friendListAdapter.update(friendInfoList);
                }

                @Override
                public void onFriendListAdded(ZIM zim, ArrayList<ZIMFriendInfo> friendInfoList) {
                    friendListAdapter.add(friendInfoList);
                }

                @Override
                public void onFriendListDeleted(ZIM zim, ArrayList<ZIMFriendInfo> friendInfoList) {
                    friendListAdapter.delete(friendInfoList);
                }
            });

        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onFriendListQueried(ArrayList<ZIMFriendInfo> friendList, int nextFlag,
                                    ZIMError zimError) {
        AppLogger.getInstance().d(
                "onFriendListQueried friendList: %s",
                new Gson().toJson(friendList));

        friendListAdapter.addAll(friendList);

    }
}
